//
//  CorgiOAuthViewController.swift
//  weibo
//
//  Created by Corgi on 17/3/22.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit
import SVProgressHUD

class CorgiOAuthViewController: UIViewController {

    ///webView懒加载
    private lazy var webView = UIWebView()
    
    ///loadView时,访问self.view,更改为webView,不能>>super!!!<<<
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    ///关闭按钮,dismiss
    @objc private func close() {
        
        self.dismiss(animated: true, completion: nil)
        
    }
    
    ///viewDidLoad中进行控件布局
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.isOpaque = false
        
        //关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        
        //走后门
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", imageName: "", backImageName: "", target: self, action: #selector(defaultAccount))
        
        //loadView加载Request
        loadOAuthPage()
    }
    
    ///走后门
    @objc private func defaultAccount() {
        
        let jsString = "document.getElementById('userId').value = 'shisiloudajiangyou@live.cn' , document.getElementById('passwd').value = 'corgi14' , document.getElementById('passwd').value = 'corgi14'"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
    ///即将消失,HUD消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //消失
        SVProgressHUD.dismiss()
    }
    
    ///加载网页
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "4037818929" + "&redirect_uri=" + "http://www.baidu.com"
        
        let url = URL(string: urlString)
        
        guard let u = url else {
            return
        }
        
        let request = URLRequest(url: u)
        
        webView.loadRequest(request)
    }
    
}

///Extension的用法,遵守代理,复写协议方法,模块化
extension CorgiOAuthViewController: UIWebViewDelegate {

    //webView代理方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        //开启提示
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //结束提示
        SVProgressHUD.dismiss()
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //报错
        SVProgressHUD.showError(withStatus: "error")
        
    }
    
    ///截取网络访问,获取url
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取URLString
        let urlString = request.url?.absoluteString ?? ""
        
        //判断是否包含code
        let flag = "code="
        
        if urlString.contains(flag) {
            //授权成功,截取code
            //获取url中参数
            let query = request.url?.query ?? ""
            
            let code = query.substring(from: flag.endIndex)
            
            //通过code请求token
            CorgiUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (success) in
                
                if !success {
                
                    SVProgressHUD.showError(withStatus: "请求错误")
            
                }
                //设置根视图控制器
                //UIApplication.shared.keyWindow?.rootViewController = CorgiWelcomeViewController()
                
                self.dismiss(animated: true, completion: {
                    
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: SWITCHROOTVIEWCONTROLLERNOTI), object: nil)
                    
                })
                
            })
            
            return false
        }
        
        return true
    }

    /*
    ///token请求,获得令牌
    private func loadAccessToken(code: String) {
        
        //token url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let para = ["client_id" : client_id,
                    "client_secret" : client_secret,
                    "grant_type" : "authorization_code",
                    "code" : code,
                    "redirect_uri" : redirect_uri]
        
        //发送网络请求,获取token
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, paramters: para) { (result, error) in
            
            if error != nil {
            
                SVProgressHUD.showError(withStatus: "网络错误")
            
                return
            }
            
            //获取token成功,发送网络请求,获取用户信息
            self.loadUserInfo(result as! [String : Any])
            
        }
    }

    ///获取用户信息
    private func loadUserInfo(_ dict: [String : Any]) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let token = dict["access_token"]
        
        let uid = dict["uid"]

        let para = ["access_token" : token,
                    "uid" : uid]
        
        //发送网络请求
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, paramters: para) { (result, error) in
            
            if error != nil {
            
                SVProgressHUD.showError(withStatus: "网络错误")
                
                return
            }
            
            var userInfoDict = result as! [String : Any]
            
            //遍历dict,与userInfoDict合并
            for (key, value) in dict {
            
                userInfoDict[key] = value
            
            }
            
            //字典转模型
            let userAccountModel = CorgiUserAccountModel(dict: userInfoDict)
            
            //归档
            let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
            
            print(path)
            
            NSKeyedArchiver.archiveRootObject(userAccountModel, toFile: path)
        }
    }
   */
}
